/**
 * 
 */
package shellInterface;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import others.Global;

/**
*@author tonychao 
*功能 用于调用Linux shell 的函数，要求单线程，阻塞，将标准输出打印至屏幕，标准输入并不进行处理
*/

public class LinuxShell {
	
	public static ArrayList<String> runInSequence(ArrayList<String> commandArray) throws IOException, InterruptedException{
		return runInSequence(commandArray,new ArrayList<String>());
	}
	
	//串行在linux中执行一系列命令
	public static ArrayList<String> runInSequence(ArrayList<String> commandArray,ArrayList<String> hintArray) throws IOException, InterruptedException{
		if (!Global.SUBMIT_COMMAND_TO_SYSYTEM){
			UserSubmitInterface_test.UIOutPut("用户选项：不提交Spark系统实际执行命令");
			return null;
		}
			
		ArrayList<String> ret =new ArrayList<String>();
		//this function works for bash now, and show it in console
		String correntCommand,correntHint;
		for(int i =0;i<commandArray.size();i++){//travel through the commands and hint arrays
			correntCommand=commandArray.get(i);
			//System.out.print(correntCommand);
			if(hintArray.size()>i+1) correntHint= hintArray.get(i);
			else correntHint =null;
			UserSubmitInterface_test.UIOutPut("shell执行任务：COMMAND:\t"+correntCommand+"\tHINT:\t"+correntHint);
			
			if(!OSinfo.isLinux()){
				//用于Windows下测试
				UserSubmitInterface_test.UIErr("非linux 操作平台略过linuxshell执行");
				return null;
			}
			Process correntProcess=Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",correntCommand+" 2>&1"});  
			//要在结束之前将程序的标准输出进行打印，否则如果程序执行时间过长，用户没有办法直接看到新的输出
			ret.add(showInConsole(correntProcess));
			//等待结束
			int retValue=correntProcess.waitFor();
			if (retValue!=0){
				UserSubmitInterface_test.UIErr(correntCommand+"执行失败，返回值：" + retValue);
				return null;
			}
		}
		return ret;
	}
	
	//将子进程的标准输出投放到控制台
	public static String showInConsole(Process process) throws IOException{
		String ret="";
		System.out.println("********以下是来自子进程的输入**********");
		//名字叫inputStream 但是连接的的子进程的out putStream
		BufferedReader stdout = new BufferedReader(new InputStreamReader(process.getInputStream()));  
		String line;
        while ((line = stdout.readLine()) != null) {  
            System.out.println(line);  
            ret= ret+line+"\n";
            }
        System.out.println("**********子进程输入结束************");
        return ret;

	}
	
}
